//
//  RegisterViewController.m
//  iphone_test2
//
//  Created by Yang Lu on 4/16/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "RegisterViewController.h"
#import "CarpoolWithFriendsAdapter.h"
#import "CarpoolWithFriendsServer.h"
#import "CarpoolWithFriendsAppDelegate.h"
#import "StreamFirstLevelViewController.h"
#import "MenusViewController.h"
#import "RevealController.h"

@implementation RegisterViewController

@synthesize nameTableView, detailTableView, uploadImage;

//hardcoded right now
#define kMin 150
#define MOVEUP_OFFSET_FIRSTNAME 0
#define MOVEUP_OFFSET_LASTNAME 0
#define MOVEUP_OFFSET_EMAIL -50
#define MOVEUP_OFFSET_PASSWORD -80
#define MOVEUP_OFFSET_PHONE -110
#define STATUSBAR_HEIGHT 0

- (IBAction)backgroundTap:(id)sender{
    [tfFirstName resignFirstResponder];
    [tfLastName resignFirstResponder];
    [tfUserEmail resignFirstResponder];
    [tfUserPassword resignFirstResponder];
    [tfUserPhone resignFirstResponder];
}

-(void)btnJoinPressed:(id)sender
{
    //trim  the input strings
    NSString *trimmedFirstName = [tfFirstName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *trimmedLastName = [tfLastName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *trimmedEmail= [tfUserEmail.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *trimmedPassword= [tfUserPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *trimmedPhone = [tfUserPhone.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    
    if( [trimmedFirstName isEqualToString:@""] == YES ||
        [trimmedLastName isEqualToString:@""] == YES ||
        [trimmedEmail isEqualToString:@""] == YES|| 
        [trimmedPassword isEqualToString:@""] == YES ||
       [trimmedPhone isEqualToString:@""] == YES
       )
    {
        // TODO: Need to modify the content
        UIAlertView *inputError = [[UIAlertView alloc] initWithTitle:@"Input Error" 
                                                             message:@"Email or Password is invalid"
                                                            delegate:self cancelButtonTitle:@"Ok"
                                                   otherButtonTitles:nil];
        [inputError show];
        [inputError release];
        
        return;
    }
    
    NSMutableDictionary *retDict;
    BOOL retVal = [CarpoolWithFriendsAdapter requestRegisterWithEmail:trimmedEmail password:trimmedPassword firstName:trimmedFirstName lastName:trimmedLastName phone:trimmedPhone retData:&retDict];

    // This is just for testing
    // if in testing mode(YES), will switch to stream view

    if(retVal == YES)
    {
//        NSString *userID = [retDict objectForKey:@"id"];
//        [CarpoolWithFriendsServer setUserID: userID];
        
        // save user login info in NSUserDefaults
//        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        //store the user info into defaults
        // ....
        
        // switch to stream view
        CarpoolWithFriendsAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];        
        StreamFirstLevelViewController *streamViewController = [[StreamFirstLevelViewController alloc] init];
        MenusViewController *menusViewControler = [[MenusViewController alloc] init];
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController: streamViewController];
        RevealController *revealController = [[RevealController alloc] initWithFrontViewController:navigationController rearViewController:menusViewControler];
        appDelegate.window.rootViewController = revealController;
        
        // animation
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:1];
        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:appDelegate.window cache:YES];
        [self.navigationController.view removeFromSuperview];
        
        [UIView commitAnimations];
        
        [navigationController release];
        [streamViewController release];
        [menusViewControler release];
        [revealController release];
        
    }
    else
    {
        UIAlertView *registerFailureError = [[UIAlertView alloc] initWithTitle:@"Register Failure" 
                                                                       message:@"Email is already registered"
                                                                      delegate:self cancelButtonTitle:@"Ok"
                                                             otherButtonTitles:nil];
        [registerFailureError show];
        [registerFailureError release];
    }
    
}

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */


/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */

/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // remove the background of table views
    nameTableView.backgroundColor = [UIColor clearColor];
    nameTableView.opaque = NO;
    
    detailTableView.backgroundColor = [UIColor clearColor];
    detailTableView.opaque = NO;
    
    // differentiat the two table views based on tag
    nameTableView.tag = 0;
    detailTableView.tag = 1;
    
    // add right nav button to nav bar
    if (![self.navigationItem rightBarButtonItem])
    {
        // If not, allocate one and add it.
        UIBarButtonItem *joinBtn = [[UIBarButtonItem alloc] initWithTitle:@"Join" style:UIBarButtonItemStylePlain target:self action:@selector(btnJoinPressed:)];
        
        self.navigationItem.rightBarButtonItem = joinBtn;
        [joinBtn release];
    }
    
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification object:self.view.window]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification object:self.view.window];
}

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations.
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [tfFirstName release];
    [tfLastName release];
    [tfUserEmail release];
    [tfUserPassword release];
    [tfUserPhone release];
    [currTextField release];
    
    [nameTableView release];
    [detailTableView release];
    [uploadImage release];
    
    [super dealloc];
}

//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
    NSInteger moveup_offset = 0;
    switch (currTextField.tag) {
        case 0:
            moveup_offset = MOVEUP_OFFSET_FIRSTNAME;
            break;
        case 1:
            moveup_offset = MOVEUP_OFFSET_LASTNAME;
            break;
        case 2:
            moveup_offset = MOVEUP_OFFSET_EMAIL;
            break;
        case 3:
            moveup_offset = MOVEUP_OFFSET_PASSWORD;
            break;
        case 4:
            moveup_offset = MOVEUP_OFFSET_PHONE;
            break;
        default:
            break;
    }
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3]; // if you want to slide up the view
    
    CGRect rect = self.view.frame;
    if (movedUp)
    {
        // 1. move the view's origin up so that the text field that will be hidden come above the keyboard 
        // 2. increase the size of the view so that the area behind the keyboard is covered up.
        rect.origin.y = moveup_offset;//kMin - currTextField.frame.origin.y ;
    }
    else
    {
        // revert back to the normal state.
        rect.origin.y = STATUSBAR_HEIGHT;
    }
    self.view.frame = rect;
    
    [UIView commitAnimations];
}

- (void)keyboardWillShow:(NSNotification *)notif
{
    //keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriatelyå
    //    debug(@"%d, %@", 1, @"Kai Wang");
    
    if ([currTextField isFirstResponder] && currTextField.frame.origin.y + self.view.frame.origin.y >= kMin)
    {
        [self setViewMovedUp:YES];
    }
    else if (![currTextField isFirstResponder] && currTextField.frame.origin.y  + self.view.frame.origin.y < kMin)
    {
        [self setViewMovedUp:NO];
    }
}

- (void)keyboardWillHide:(NSNotification *)notif
{
    //keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately
    if (self.view.frame.origin.y < 0 ) {
        [self setViewMovedUp:NO];
    }
}


#pragma mark - Text Field Delegate

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
    if (currTextField) {
        [currTextField release];
    }
    currTextField = [sender retain];
    
    //move the main view, so that the keyboard does not hide it.
    //if (self.view.frame.origin.y + currTextField.frame.origin.y >= kMin) {
//    NSLog(@"self.view.frame.origin.y:%f", self.view.frame.origin.y );
//    NSLog(@"frame.origin.y:%f", currTextField.frame.origin.y );
    [self setViewMovedUp:YES];    
    //}
}

#pragma mark - Table view data source
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if([tableView tag] == 0)
    {
        return 2;
    }
    else if([tableView tag] == 1)
    {
        return 3;
    }
    return -1;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return nil;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        // if name table view
        if([tableView tag] == 0)
        {
            // set textfield
            if(indexPath.row == 0)
            {
                tfFirstName= [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 200, 35)];
                tfFirstName.tag = 0;
                tfFirstName.placeholder = @"First Name";
                tfFirstName.delegate = self;
                
                [cell.contentView addSubview:tfFirstName];
            }
            else if(indexPath.row == 1)
            {
                tfLastName= [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 200, 35)];
                tfLastName.tag = 1;
                tfLastName.placeholder = @"Last Name";
                tfLastName.delegate = self;
                
                [cell.contentView addSubview:tfLastName];
            }
        }
        // if detail table view
        else if([tableView tag] == 1)
        {
            if(indexPath.row == 0)
            {
                tfUserEmail= [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 200, 35)];
                tfUserEmail.tag = 2;
                tfUserEmail.placeholder = @"Email";
                tfUserEmail.delegate = self;
                
                [cell.contentView addSubview:tfUserEmail];
            }
            else if(indexPath.row == 1)
            {
                tfUserPassword= [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 200, 35)];
                tfUserPassword.tag = 3;
                tfUserPassword.placeholder = @"Password";
                tfUserPassword.delegate = self;
                
                [cell.contentView addSubview:tfUserPassword];
                
            }
            else if(indexPath.row == 2)
            {
                tfUserPhone= [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 200, 35)];
                tfUserPhone.tag = 4;
                tfUserPhone.placeholder = @"Phone";
                tfUserPhone.delegate = self;
                
                [cell.contentView addSubview:tfUserPhone];
            }
        }
    }
    
    return cell;
}

@end
